package com.nhh.v.controller

import java.util.UUID
import java.{util ⇒ jul}
import javax.validation.Valid

import com.nhh.gt.sdk.GeetestLib
import com.nhh.v.anotation.{ClientAddress, ValidateHeader}
import com.nhh.v.cons.ServerCons
import com.nhh.v.dto.RequiredRequestHeader
import com.nhh.v.model.NhhwakHashrateRanking
import com.nhh.v.service.{HashRateService, ResultData, UsersService}
import com.nhh.v.utils.{JsonUtil, NhhUtil}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation._
import reactor.core.publisher.Mono

/**
  * Created by ywp on 2018/9/4.
  */
@RestController
@RequestMapping(path = Array("/api/user"))
@Validated
class UserController(@Autowired val usersService: UsersService,
                     @Autowired val hashRateService: HashRateService) {


  @PostMapping(path = Array("updateNickname"))
  def updateNickname(@Valid @ValidateHeader requireHeader: RequiredRequestHeader,
                  @RequestParam(value = "nickname") nickname: String
                 ): Mono[_] = {
    Mono.just(usersService.updateNickname(nickname, requireHeader.getUid))
  }

  @PostMapping(path = Array("qryHashrateRank"))
  def qryHashRateRank(@Valid @ValidateHeader requireHeader: RequiredRequestHeader,
                      @RequestParam(value = "psize", required = false, defaultValue = "20") pSize: String,
                      @RequestParam(value = "pindex", required = false, defaultValue = "0") pIndex: String
                     ): Mono[_] = {
    Mono.just(HashRateRank(rows = hashRateService.qryHashRateRank(requireHeader.getUid.toInt, pIndex, pSize), psize = pSize))
  }

  @PostMapping(path = Array("getuser"))
  def getUser(@Valid @ValidateHeader requireHeader: RequiredRequestHeader): Mono[_] = {
    Mono.just(usersService.getUser(requireHeader.getUid))
  }


  @PostMapping(path = Array("initGt"))
  def initGeeTest(@ClientAddress ipAddress: String): Mono[_] = {
    val fakeSessionId = UUID.randomUUID().toString
    val gtSdk = new GeetestLib(ServerCons.GEETEST_CAPTCHA_ID, ServerCons.GEETEST_PRIVATE_KEY, false)
    val data = new jul.HashMap[String, String]()
    data.put("user_id", fakeSessionId)
    data.put("client_type", "web")
    data.put("ip_address", ipAddress)
    //status、user_id客户端存储
    val status = gtSdk.preProcess(data)
    val gtResponseMap = JsonUtil.asJavaObj[jul.Map[String, Object]](gtSdk.getResponseStr, classOf[jul.Map[String, Object]])
    gtResponseMap.put("user_id", fakeSessionId)
    gtResponseMap.put("gt_status", Integer.valueOf(status))
    Mono.just(gtResponseMap)
  }

  @PostMapping(path = Array("getcode"))
  def getCode(@RequestParam(value = "type", required = false, defaultValue = "login") `type`: String,
              @RequestParam(value = "gt_status") status: Int,
              @RequestParam(value = "user_id") userId: String,
              @RequestParam(value = "phone") phone: String,
              @RequestParam(value = "areaCode") areaCode: String,
              @RequestParam(value = "geetest_challenge") gtChallenge: String,
              @RequestParam(value = "geetest_validate") gtValidate: String,
              @RequestParam(value = "geetest_seccode") gtSecCode: String,
              @ClientAddress ipAddress: String
             ): Mono[_] = {


         NhhUtil.isMobile("")


    //    $rtn=array('retCode'=>'0','retMsg'=>'');
    //    $type=$this->request('type')?:'login';
    //    $areaCode=$this->request('areaCode');
    //    $tel = $this->request("phone");
    //    if(!Utility::is_mobile($areaCode.$tel))
    //    {
    //      $rtn=Utility::setRetCode($rtn,'error_mobile');
    //      $this->out_json($rtn);
    //      return false;
    //    }
    //    if($type=='login')
    //    {
    //      require_once APPPATH . '/libraries/gt3-php-sdk/lib/class.geetestlib.php';
    //      require_once APPPATH . '/config/config.php';
    //      $captcha_id = config_item('CAPTCHA_ID');
    //      $private_key = config_item('PRIVATE_KEY');
    //      $GtSdk = new GeetestLib($captcha_id, $private_key);
    //      session_start();
    //      $data = array(
    //        "user_id" => $_SESSION['user_id'],
    //      "client_type" => "web",
    //      "ip_address" => $this->input->ip_address()
    //      );
    //      $geetest_challenge = $this->request("geetest_challenge");
    //      $geetest_validate = $this->request("geetest_validate");
    //      $geetest_seccode = $this->request("geetest_seccode");
    //      if ($_SESSION['gtserver'] == 1) {   // geetest is ok
    //      $result = $GtSdk->success_validate($geetest_challenge, $geetest_validate, $geetest_seccode, $data);
    //      if (!$result) {
    //        $this->output->set_output('{"status":"fail"}');
    //        return false;
    //      }
    //    } else {  // geetest is down fallback
    //      if ($GtSdk->fail_validate($geetest_challenge, $geetest_validate, $geetest_seccode)) {
    //      } else {
    //        $this->output->set_output('{"status":"fail"}');
    //        return false;
    //      }
    //    }
    //    }
    //    $verifyCode = rand(100000,999999);
    //    $this->load->model('Verifycode_Model','verify');
    //    $rtn=$this->verify->verifyCodeAdd(array('phone'=>$areaCode.$tel,'verifyCode'=>$verifyCode,'type'=>$type, 'ipAddr' => $this->input->ip_address()),$type,$this->input->ip_address());
    //    if($rtn['retCode']=='0')
    //    {
    //      $this->load->library('yunpian_interface');
    //      $rtn=$this->yunpian_interface->send_verification_code($areaCode.$tel,$verifyCode);
    //    }
    //
    //    $this->out_json($rtn);

    Mono.just(null)
  }
}

case class HashRateRank(rows: jul.List[NhhwakHashrateRanking], psize: String) extends ResultData
